local Grid = {}
local Cell = require('scripts.models.Cell')
-- structure determines the level characteristics

function Grid:new(rows, cols, colWidth, colHeight, structure)
	local grid = display.newGroup()
-- statics
	grid.rows = rows
	grid.cols = cols
	grid.gridWidth = colWidth * rows
	grid.gridHeight = colHeight * cols
	grid.cellWidth = colWidth
	grid.cellHeight = colHeight
	grid.cells = {}
	-- print (rows, cols)
	for i = 1, rows do
		table.insert(grid.cells, {})
		for j = 1, cols do
			-- print (i, j)
			local cell, cellConfig = nil, structure[i][j]
			cell = Grid:createCell(cellConfig, i, j, grid.cellWidth, grid.cellHeight)
			table.insert(grid.cells[i], cell)
			grid:insert(cell)
		end
	end

	function grid:update(delta) 
	end

	function grid:getCellFromCoordinates(x, y)
		local col = math.floor(x / self.cellWidth) + 1
		local row = math.floor(y / self.cellHeight) + 1
		local cell = nil
		if row > 0 and row <= self.rows and col > 0 and col <= self.cols then
			cell = self.cells[row][col]
			-- print (row, col, self.cells[row][col].cellType, x, y)
		end
		return cell
	end
	return grid
end
--factory method for creating cells
function Grid:createCell(cellConfig, i, j, w, h)
	local cell = nil
	local centerX = w / 2 + w * (j - 1)
	local centerY = h / 2 + h * (i - 1)
	--todo add sprite map

	cell = Cell:new(centerX, centerY, w , h , i, j, cellConfig)
	return cell
end

return Grid